<template>
    <page-container title="设置" :showBack="true">
        <template v-slot:nav-left>
            <view class="nav-left" @click="goBack">
                <uni-icons type="left" size="20" color="#d4af37"></uni-icons>
            </view>
        </template>
        <view class="setting-container">
            <!-- 设置列表 -->
            <view class="setting-list">
                <view class="setting-item" @click="goToAvatar">
                    <text class="item-text">个人头像</text>
                    <view class="item-right">
                        <image class="avatar-icon" v-if="avatarUrl" :src="avatarUrl" mode="aspectFit"></image>
                        <image class="avatar-icon" v-else src="/static/header.png" mode="aspectFit"></image>
                        <image class="arrow-icon" src="/static/index/gray-right.png" mode="aspectFit"></image>
                    </view>
                </view>

                <view class="setting-item" @click="goToChangePassword">
                    <text class="item-text">修改密码</text>
                    <view class="item-right">
                        <image class="arrow-icon" src="/static/index/gray-right.png" mode="aspectFit"></image>
                    </view>
                </view>
            </view>

            <!-- 退出按钮 -->
            <view class="logout-section">
                <button class="logout-btn" @click="handleLogout">退出</button>
            </view>
        </view>
    </page-container>
</template>

<script>
import config from '@/config'
import { uploadToOss } from '@/utils/ossUpload'
export default {
    name: 'Setting',
    data() {
        return {
            avatarUrl: '/static/header.png'
        }
    },
    onShow() {
        this.avatarUrl = uni.getStorageSync('customerInfo') ? uni.getStorageSync('customerInfo').avatar : '/static/header.png'
    },
    methods: {
        goBack() {
            setTimeout(() => {
                uni.navigateBack()
            }, 100)
        },
        // 跳转到个人头像页面
        goToAvatar() {
            uni.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: (res) => {
                    const filePath = res.tempFilePaths[0]
                    this.avatarUrl = filePath
                    uni.getFileInfo({
                        filePath: filePath,
                        success: async (fileInfo) => {
                            const maxSize = 5 * 1024 * 1024 // 5MB
                            if (fileInfo.size > maxSize) {
                                uni.showToast({
                                    title: '图片大小不能超过5M',
                                    icon: 'none'
                                })
                                return
                            }
                            // 显示上传进度
                            uni.showLoading({
                                title: '上传中...'
                            })

                            let fileSuffix = `${res.tempFiles[0].path.split('.').pop()}`
                            let OssParams = {
                                filePath,
                                dir: config.ossConfig.ossDevDepositAddress, // 可选，不传读 config.ossConfig.ossDevDepositAddress
                                ext: fileSuffix           // 可选
                            }
                            // #ifdef H5
                            OssParams.filePath = res.tempFiles[0]
                            // #endif
                            const { key, url } = await uploadToOss(OssParams)
                            uni.hideLoading()
                            this.$http.post('/applet/customer/updateAvatar', {
                                cusId: uni.getStorageSync('customerInfo').id,
                                avatar: key
                            }).then(res => {
                                this.getCustomerInfo()
                                uni.showToast({
                                    title: '更新头像成功',
                                    icon: 'success'
                                })
                            })

                            return
                            client.put(`${config.ossConfig.ossDevDepositAddress}${new Date().getTime()}${fileSuffix}`, res.tempFiles[0]).then(res => {

                                uni.hideLoading()
                                this.$http.post('/applet/customer/updateAvatar', {
                                    cusId: uni.getStorageSync('customerInfo').id,
                                    avatar: res.name
                                }).then(res => {
                                    this.getCustomerInfo()
                                    uni.showToast({
                                        title: '更新头像成功',
                                        icon: 'success'
                                    })
                                })
                            }).catch(error => {
                                uni.hideLoading()
                                console.error('OSS上传失败:', error)
                                uni.showToast({
                                    title: 'OSS上传失败，请重试',
                                    icon: 'none'
                                })
                            })

                        }
                    })
                },
                fail: (err) => {
                    uni.showToast({
                        title: '上传失败',
                        icon: 'none'
                    })
                },
                complete: () => {
                    uni.hideLoading()
                }
            })
        },
        getCustomerInfo() {
            this.$http.get('/applet/customer/info').then(res => {
                uni.setStorageSync('customerInfo', res.data || {})
            })
        },
        // 跳转到修改密码页面
        goToChangePassword() {
            uni.navigateTo({
                url: '/pages/mine/changePwd/index'
            })
        },

        // 退出登录
        handleLogout() {
            uni.showModal({
                title: '提示',
                content: '确定要退出登录吗？',
                success: (res) => {
                    if (res.confirm) {
                        this.$http.get('/applet/customer/logout').then(res => {
                            uni.showToast({
                                title: res.data,
                                icon: 'success'
                            })
                            // 清除登录状态
                            uni.removeStorageSync('token')
                            uni.removeStorageSync('customerInfo')
                            // uni.removeStorageSync('stsTokenExpiration')
                            // uni.removeStorageSync('stsToken')
                            // 跳转到登录页
                            // #ifdef MP-WEIXIN
                            uni.redirectTo({
                                url: '/pages/login/quick',
                            })
                            // #endif
                            // #ifdef H5
                            uni.reLaunch({
                                url: '/pages/login/index'
                            })
                            // #endif
                        })
                    }
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.setting-container {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding: 20rpx;
}

.setting-list {
    background-color: #ffffff;
    border-radius: 12rpx;
    overflow: hidden;
    margin-bottom: 40rpx;
}

.setting-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx 20rpx;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
        border-bottom: none;
    }
}

.item-text {
    font-size: 32rpx;
    color: #333333;
    font-weight: 500;
}

.item-right {
    display: flex;
    align-items: center;
}

.avatar-icon {
    width: 80rpx;
    height: 80rpx;
    margin-right: 20rpx;
    border-radius: 50%;
    border: 1rpx solid #EEEEEE;
}

.arrow-icon {
    width: 32rpx;
    height: 32rpx;
}

.logout-section {
    padding: 0 20rpx;
}

.logout-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background-color: #383838;
    color: $uni-text-color-orange;
    border: none;
    border-radius: 16rpx;
    font-size: 30rpx;
    letter-spacing: 2rpx;

    &:active {
        background-color: #383838;
    }
}
</style>
